package com.fenghongzhang.day008;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class Main2Activity extends AppCompatActivity {
    private EditText username;
    private EditText password;
    private CheckBox cbRemember;
    private Button login;
    private SharedPreferences sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);


        /**
         * 输入用户名和密码
         * 登录的时候,如果多选框被选中,则记住用户名和密码
         * 下次直接取来,填入到输入框中即可
         */
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        cbRemember = (CheckBox) findViewById(R.id.cb_remember);
        login = (Button) findViewById(R.id.login);


        sp = getSharedPreferences("login", MODE_PRIVATE);
        boolean isLogin = sp.getBoolean("isLogin", false);
        if (isLogin){
            //直接取
            String name = sp.getString("name", "");
            String pwd = sp.getString("pwd", "");
            username.setText(name);
            password.setText(pwd);
            cbRemember.setChecked(true);
        }
        this.login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断状态
                if(cbRemember.isChecked()){//选中
                    String name = username.getText().toString();
                    String pwd = password.getText().toString();
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("name",name);
                    edit.putString("pwd",pwd);
                    //状态
                    edit.putBoolean("isLogin",true);
                    edit.commit();
                }else{
                    SharedPreferences.Editor edit = sp.edit();
                    edit.clear();
                    edit.commit();
                }
            }
        });


    }
}
